rm(list= ls())

library(fixest)
library(tidyverse)

## Dict

setFixest_dict(c(cdu_csu_party = "CDU/CSU",
                 afd_party = 'AfD',
                 right_total_party_nofdp = "CDU/CSU/AfD combined",
                 unem_rate_2013 = "Unemployment rate (%)"))


#### Bundestag data ####

bt <- readRDS('data/federal_elections_clean.RDS') %>%
  mutate(year = date.id) 

## Get unemployment rate at county level 

unemp <- readRDS('data/unemp_county_2014.rds')

# Data, outcomes, checks

bt_use <- bt %>% filter(year %in% c(2013, 2017))

dvars <- c("right_total_party_nofdp",
           "left_total_party",
           'afd_party',
           'cdu_csu_party',
           'spd_party',
           'fdp_party',
           'greens_party',
           'left_party')

## Difference the DVs 

wide_df <- bt_use %>%
  pivot_wider(id_cols = 'ags',
              values_from = all_of(dvars),
              names_from = 'date.id') %>%
  mutate(right_total_party_nofdp = right_total_party_nofdp_2017 - right_total_party_nofdp_2013,
         left_total_party = left_total_party_2017 - left_total_party_2013,
         afd_party = afd_party_2017 - afd_party_2013,
         cdu_csu_party = cdu_csu_party_2017 - cdu_csu_party_2013,
         spd_party = spd_party_2017 - spd_party_2013,
         fdp_party = fdp_party_2017 - fdp_party_2013,
         greens_party = greens_party_2017 - greens_party_2013,
         left_party = left_party_2017 - left_party_2013) %>%
  left_join(bt_use %>% 
              dplyr::select('ags', 'AA.district.id', 'state') %>% 
              distinct(ags,.keep_all = T)) %>%
  mutate(county_id = substr(ags, 1, 5)) %>% 
  left_join(unemp, by = c('county_id' = 'ags'))

## Regressions with all outcomes ##

m1 <- fixest::feols(c(cdu_csu_party, afd_party, right_total_party_nofdp) ~ AA.district.id + unemp_rate_county_2014, 
                    data = wide_df,
                    cluster = 'county_id')

## Table 

etable(m1, style.tex = style.tex("qje"), 
       keep = 'unemp_rate_county_2014',
       fitstat = ~ r2 + n, tex = TRUE, 
       title = "Main results", 
       placement = '!h', label = 'tab:tab', digits = 4, digits.stats = 3)




